from flask import Flask, render_template, request,url_for,redirect
import random_saying, walk,os,random
from log import log_request

app = Flask(__name__)

@app.route('/')
def hello_world():
    """网站index页，点进进入欢迎页面"""
    title = 'study-sharing web'
    return render_template('index.html',
                           the_title=title, )

@app.route('/Welcome')
def welcome() -> 'html':
    """欢迎页，生成随机鼓励语；选择登陆或注册功能"""
    saying = random_saying.saying_making()  #引用random_saying函数，在欢迎页面上随机为用户生成一句鼓励语
    print(saying)
    return render_template('welcome.html',
                           saying=saying)

@app.route('/Signup')
def signup() -> 'html':
    """用户注册页面，填写注册用户信息"""
    return render_template('register.html')

@app.route('/register', methods=['POST'])
def register():
    """用户注册提交"""
    username = request.form['username']  #username为用户表单中所提交的username
    password = request.form['password']  #password为用户表单中所提交的password
    results = str(username)
    log_request(request,results)         #将所提交的用户名转化为str记录到日志中，为保护隐私password不计入
    with open(username+'.txt', 'w') as f:   #注册的用户会自动创建一个对应的以用户名为命名的TXT文件
        f.write(str(password))              #TXT文件中储存着用户在表单中提交的password
        return redirect(url_for('logging')) #完成创建后，点击button进入登录页面

@app.route('/logging')
def logging() -> 'html':
    """用户登录输入页面"""
    return render_template('login.html')

@app.route('/login', methods=['POST'])
def login():
    """用户登录信息提交"""
    username = request.form['username']   #username为用户表单中所提交的username
    password = request.form['password']   #password为用户表单中所提交的password
    results = str(username)               #将所提交的用户名转化为str记录到日志中，为保护隐私password不计入
    log_request(request,results)
    if username+'.txt' not in os.listdir():             #根据是否存在用户所键入的账户来跳转到不同的页面
        return render_template('username-noexist.html')
    with open(username+'.txt', 'r') as f:
        f_password = f.read()
    if username+'.txt' in os.listdir() and password == f_password:
        return redirect(url_for('home', username=username))
    elif password != f_password:
        return render_template('wrongpassword.html')

@app.route('/Home')
def home() -> 'html':
    """网站首页"""
    title = 'This is my study website.'
    username = request.args.get('username') #接受login传过来的username参数，保持登录状态
    return render_template('home.html',
                           the_title=title,
                           username=username)

@app.route('/Python')
def python() -> 'html':
    """Python分类页面"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('category-Python.html',
                           username=username)

@app.route('/API')
def API() -> 'html':
    """API分类页面"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('category-API.html',
                           username=username)

@app.route('/Others')
def Others() -> 'html':
    """Others分类页面"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('category-Others.html',
                           username=username)

@app.route('/wordbook-choice', methods=['GET', 'POST'])
def function_choose() -> 'html':
    """选择单词本所执行的功能"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('word-choice.html',
                           username=username,)

@app.route('/word-record', methods=['POST'])
def record() -> 'html':
    """输入需要记录的单词"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('word-record.html',
                           username=username,)

@app.route('/word-recording', methods=['POST'])
def recording():
    """提交，将单词记录到单词本中"""
    title = '单词已成功添加至单词本'
    word = request.form['word']
    meaning = request.form['meaning']
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    v = open(username+'-wordbook.txt', 'a', encoding='utf-8')  #记入单词本的过程中，有单词本的用户则计入到对应的单词本中，没有单词本的用户则为其创建一个单词本
    print(word+'!'+meaning, file=v)
    v.close()
    E_results = str(word)           #将用户提交的英文单词计入日志中
    C_results = str(meaning)        #将用户提交的中文含义计入日志中
    log_request(request,E_results)
    log_request(request, C_results)
    return render_template('word-record-successful.html',
                           the_title=title,
                           username=username,)

@app.route('/view-wordbook', methods=['POST'])
def viewthewordbook():
    """查看单词本"""
    title = 'Word List'
    username = request.args.get('username')     #接受上一个页面传过来的username参数，保持登录状态
    if username+'-wordbook.txt' in os.listdir():   #判断用户是否有单词本，有则显示单词本内容，没有则提醒用户先去创建
        w = open(username + '-wordbook.txt', 'r', encoding='utf-8')
        word_list = w.read()
        wordlist = word_list.replace('!', ' ')
        print(wordlist, end='')
        w.close()
        return render_template('view-wordbook.html', username=username, the_title=title,the_wordlist=wordlist)
    elif username+'-wordbook.txt' not in os.listdir():
        return render_template('wordbook-noexist.html', username=username)

@app.route('/recite-wordbook', methods=['GET'])
def recite():
    """背单词功能-用户输入答案"""
    username = request.args.get('username')    #接受上一个页面传过来的username参数，保持登录状态
    with open(username+'-wordbook.txt', 'r', encoding='utf-8') as w:   #从用户的单词本中随机抽取单词
        words = w.readlines()
    random_word = random.choice(words)
    word = random_word.split('!')   #因为TXT所计入的格式为一个英文一个中文为一行，，因此分割用户单词本中每行的中英文实现单独显示
    English = word[0]
    Chinese = word[1]
    return render_template('word-recite.html',
                    English=English,
                    Chinese=Chinese,
                    username=username)

@app.route('/reciting', methods=['POST'])
def reciting():
    """背单词功能-结果反馈"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    English = request.args.get('English')     #接收在'/recite-wordbook'中随机出来的英文单词
    Chinese = request.args.get('Chinese')     #接收在'/recite-wordbook'中随机出来的中文意思
    input_English = request.form['english']   #接收用户所提交的答案进行判断
    results = str(input_English)
    log_request(request,results)              #将用户此次背单词的操作录入日志中
    if input_English == English:              #若答案正确则返回到'/recite-wordbook'重新执行recite（）函数随机出现新的单词
        return redirect(url_for('recite', username=username))
    else:                                     #若答案错误则连同刚刚接收到的所有参数一起返回到'word-recite的html'，此时参数没有改变，用户可以再次尝试输入
        return render_template('word-recite.html',
                               Chinese=Chinese,
                               English=English,
                               username=username)

@app.route('/Python-passage')
def Python_passage():
    """购物车文章页面"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('passage-python.html',
                           username=username)

@app.route('/geo_func')
def base():
    """高德API功能，信息填写"""
    title = '步行路线规划'
    username = request.args.get('username')    #接受上一个页面传过来的username参数，保持登录状态
    return render_template('geo_func_entry.html',
                           the_title=title,
                           username=username)

@app.route('/geo_func_result', methods=['POST'])
def route_search() -> 'html':
    """高德API功能结果反馈"""
    key = request.form['key']
    start_address = request.form['start_address']
    end_address = request.form['end_address']
    title = '路线规划好了，冲冲冲'
    username = request.args.get('username')    #接受上一个页面传过来的username参数，保持登录状态
    df = walk.onfoot(key, start_address, end_address)
    results = df.loc[:, ['instruction', 'distance', 'duration']]
    results.columns = ['指引', '路程', '时间']
    route = results['指引'].tolist()
    log_request(request, route)
    return render_template('geo_func_result.html',
                           the_title=title,
                           the_start_address=start_address,
                           the_end_address=end_address,
                           the_results=results,
                           username=username,
                           the_html_table=results.to_html(index=False),)

@app.route('/API-passage')
def API_passage() -> 'html':
    """API文章页面"""
    username = request.args.get('username')   #接受上一个页面传过来的username参数，保持登录状态
    return render_template('passage-API.html',
                           username=username)

@app.route('/Others-passage')
def Others_passsage() -> 'html':
    """无痛起床文章页面"""
    username = request.args.get('username')    #接受上一个页面传过来的username参数，保持登录状态
    return render_template('passage-study.html',
                           username=username)

@app.route('/Viewlog', methods=['GET'])
def view_the_log() -> 'html':
    """日志浏览界面"""
    username = request.args.get('username')    #接受上一个页面传过来的username参数，保持登录状态
    with open('WeStudyWeb.log') as log:
        contents = log.read()
        return render_template('viewlog.html',
                               contents=contents,
                               username=username)

if __name__ == '__main__':
    app.run()
